package org.psyduck.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.psyduck.admin.file.entity.SysFile;
import org.psyduck.admin.file.service.SysFileService;
import org.psyduck.common.utils.FileOperation;
import org.psyduck.common.utils.FileUtils;
import org.psyduck.common.utils.Global;
import org.psyduck.common.utils.OSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("file")
public class UploadController {

    @Autowired
    SysFileService fileService;

    @Autowired
    OSSUtils ossUtils;

    @Autowired
    FileOperation fileOperation;

    @RequestMapping("upload")
    public Map<String, String> fileUpload(MultipartFile file, HttpServletRequest request) {
        Map<String, String> map = saveFile(file);
        String externalId = request.getParameter("externalId");
        String externalType = request.getParameter("externalType");
        SysFile sysFile = new SysFile();
        sysFile.setUrl(map.get("url"));
        sysFile.setExternalId(externalId);
        sysFile.setExternalType(externalType);
        fileService.save(sysFile);
        return map;
    }

    @RequestMapping("resort")
    public void resort(String... urls) throws UnsupportedEncodingException {
        for (int i = 0; i < urls.length; i++) {
            String url = urls[i];
            String id = fileService.getDao().selectOne(new QueryWrapper<SysFile>().eq("url", URLDecoder.decode(url, "UTF-8"))).getId();
            SysFile sysFile = new SysFile();
            sysFile.setSort(i + 1);
            sysFile.setId(id);
            fileService.updateById(sysFile);
        }
    }

    @RequestMapping("getFiles")
    public List<String> getFiles(String externalId, String externalType){
        List<SysFile> files = fileService.getDao().selectList(new QueryWrapper<SysFile>().eq("external_id", externalId).eq("external_type", externalType).orderByAsc("sort"));
        return files.stream().map(it -> it.getUrl()).collect(Collectors.toList());
    }

    @RequestMapping("delete")
    public void delete(String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, "UTF-8");
        fileService.remove(new QueryWrapper<SysFile>().eq("url", url));
        if(!(Global.UPLOAD_TYPE.equals("oss") && !ossUtils.isDefault())){
            url = url.substring(0, url.lastIndexOf("/"));
        }
        fileOperation.fileDelete(url);
    }

    public Map<String, String> saveFile(MultipartFile file) {
        Map<String, String> map = new HashMap<>();
        if(Global.UPLOAD_TYPE.equals("oss") && !ossUtils.isDefault()){
            try {
                map = ossUtils.uploadFileToOss(file.getOriginalFilename(),file.getBytes(),file.getInputStream());
            }catch (Exception ignore){}
        }else{
            map = FileUtils.saveFile(file);
        }
        return map;
    }

    @RequestMapping("cropper")
    public Map<String, String> cropper(MultipartFile file, String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, "UTF-8");
        fileOperation.fileDelete(url);
        Map<String, String> map = saveFile(file);
        SysFile sysFile = new SysFile();
        sysFile.setUrl(map.get("url"));
        fileService.update(sysFile, new QueryWrapper<SysFile>().eq("url", url));
        return map;
    }

}
